import { createRouter, createWebHashHistory } from 'vue-router'
import store from '../store/index.js'

const routes = [
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '校园订餐系统-登录',
      requiresAuth: false
    },
    component: () => import('@/views/front/Login.vue')
  },
  ,
  {
    path: '/register',
    name: 'register',
    meta: {
      title: '校园订餐系统-注册',
      requiresAuth: false
    },
    component: () => import('@/views/front/Reg.vue')
  },
  {
    path: '/',
    name: 'Index',
    meta: {
      title: '校园订餐系统-首页',
      requiresAuth: false
    },
    component: () => import('@/views/front/Index.vue')
  },
  {
    path: '/shop-list',
    name: 'shop-list',
    meta: {
      title: '校园订餐系统-店铺列表',
      requiresAuth: true
    },
    component: () => import('@/views/front/Shop-list.vue')
  },
  {
    path: '/shop-detail/:id',
    name: 'shop-detail',
    meta: {
      title: '校园订餐系统-店铺详情',
      requiresAuth: true
    },
    component: () => import('@/views/front/Shop-detail.vue')
  },
  {
    path: '/shopping-cart/:id',
    name: 'ShoppingCart',
    meta: {
      title: '校园订餐系统-购物车',
      requiresAuth: true
    },
    component: () => import('@/views/front/ShoppingCart.vue')
  },
  {
    path: '/order-list',
    name: 'OrderList',
    meta: {
      title: '校园订餐系统-我的订单',
      requiresAuth: true
    },
    component: () => import('@/views/front/Order-list.vue')
  },
  ,
  {
    path: '/collect-list',
    name: 'collect-list',
    meta: {
      title: '校园订餐系统-我收藏的店铺',
      requiresAuth: true
    },
    component: () => import('@/views/front/Collect-list.vue')
  },
  {
    path: '/admin/',
    name: 'admin',
    component: () => import('@/views/admin/Dashboard.vue'),
    children: [
      {
        path: '',
        name: 'Dashboard',
        meta: {
          title: '首页'
        },
        component: () => import('@/views/admin/Home.vue')
      },
      {
        path: 'user',
        name: 'User',
        meta: {
          title: '用户管理'
        },
        redirect: '/admin/user/userList',
        children: [
          {
            path: 'userList',
            name: 'userList',
            component: () => import('@/views/admin/User.vue'),
            meta: { title: '用户列表' }
          }
        ]
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title ? to.meta.title : '订餐系统'
  if (to.meta.requiresAuth) {
    const uInfo = store.state.uInfo.userInfo
    if (!uInfo.userName) {
      // 未登录,跳转到login
      if (to.path === '/login') {
        next()
        return
      }
      next('/login')
    } else {
      next()
    }
  } else if (to.meta.requiresAdminAuth) {
    // 后台管理员需要登录
    if (!store.state.SysuInfo.userInfo.token) {
      // 后台管理员未登录
      next('/admin/login') // 重定向到后台登录页
    } else {
      next() // 继续导航
    }
  } else {
    next()
  }
})

export default router
